const express = require('express')
const { query } = require('../utils/pool')
const router = express.Router()

// 广告添加
router.post('/add', async (req, res, next) => {
  const obj = req.body
  obj.ctime = Date.now()
  try {
    const result = await query('insert into ih_ad set ?', [obj])
  } catch (err) {
    return next(err)
  }
  res.send({ code: 200, msg: '广告添加成功' })
})
// 列表
router.get('/list', async (req, res, next) => {
  try {
    var result = await query('select * from ih_ad')
  } catch (err) {
    return next(err)
  }
  res.send({ code: 200, msg: '广告列表', data: result })
})
// 删除
router.delete('/del', async (req, res) => {
  const obj = req.query
  const result = await query('delete from ih_ad where id=?', [obj.id])
  console.log(result)

  if (result.affectedRows === 0) {
    res.send({ code: 400, msg: '删除失败' })
  } else {
    res.send({ code: 200, msg: '删除成功' })
  }
})

router.put('/update', async (req, res) => {
  const obj = req.body
  try {
    var result = await query('update ih_ad set ? where id=?', [obj, obj.id])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  if (result.changedRows === 0) {
    res.send({ code: 400, msg: '修改失败' })
  } else {
    res.send({ code: 200, msg: '修改成功' })
  }
})

module.exports = router
